package com.example.petchating.android.api

import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import com.example.petchating.network.ChatHistoryRepository

class AndroidChatDatabase(context: Context) : ChatHistoryRepository {

    private val dbHelper = object : SQLiteOpenHelper(context, "chat.db", null, 1) {
        override fun onCreate(db: SQLiteDatabase) {
            db.execSQL("CREATE TABLE IF NOT EXISTS chat (id INTEGER PRIMARY KEY AUTOINCREMENT, message TEXT, reply TEXT)")
        }

        override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
            db.execSQL("DROP TABLE IF EXISTS chat")
            onCreate(db)
        }
    }

    override fun saveChat(message: String, reply: String) {
        val db = dbHelper.writableDatabase
        val stmt = db.compileStatement("INSERT INTO chat (message, reply) VALUES (?, ?)")
        stmt.bindString(1, message)
        stmt.bindString(2, reply)
        stmt.executeInsert()
        stmt.close()
        db.close()
    }

    override fun getHistory(): List<Pair<String, String>> {
        val db = dbHelper.readableDatabase
        val cursor = db.rawQuery("SELECT message, reply FROM chat", null)
        val list = mutableListOf<Pair<String, String>>()
        while (cursor.moveToNext()) {
            list.add(cursor.getString(0) to cursor.getString(1))
        }
        cursor.close()
        db.close()
        return list
    }
}

